<template>
  <div class="app-container">
    <div class="filter-container">
      <el-date-picker v-model="listQuery.order_date" format="yyyy-MM-dd" type="datetime" style="width: 130px;" placeholder="订单日期" />
      <el-input v-model="listQuery.real_name" placeholder="姓名" style="width: 130px;margin-top:8px" class="filter-item"
        @keyup.enter.native="handleFilter" />
      <el-input v-model="listQuery.mobile" placeholder="手机号码" style="width: 130px;;margin-top:8px" class="filter-item"
        @keyup.enter.native="handleFilter" />
      <el-select v-model="listQuery.city" placeholder="选择城市" filterable class="filter-item" style="width:130px;margin-top:8px" @change="getRegionList">
        <el-option label="请选择城市"  value="" />
        <el-option
          v-for="item in city"
          :key="item.city"
          :label="item.name"
          :value="item.city"
        />
      </el-select>
      <el-select v-model="listQuery.merchant_type" placeholder="商户类型" filterable class="filter-item" style="width: 130px;">
        <el-option label="商户类型" value="" />
        <el-option value="1" label="医美"/>
        <el-option value="2" label="生美"/>
      </el-select>
      <el-select v-model="listQuery.merchant_id" placeholder="请选择商户" filterable class="filter-item" style="width: 130px;;margin-top:8px">
        <el-option label="请选择商户" value="" />
        <el-option v-for="(item,index) in merchant_list" :label="item.merchant_name" :value="item.merchant_id" />
      </el-select>
      <!-- <el-select v-model="listQuery.descrition" placeholder="请选择备注" v-if="nodes.indexOf('134')!=-1" class="filter-item" style="width:130px;margin-top:8px">
        <el-option
              v-for="item in desc_list"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
      </el-select> -->
      <el-select v-model="listQuery.order_s" placeholder="当前状态" class="filter-item" style="width:130px;margin-top:8px">
        <el-option label="当前状态" value="" />
        <el-option label="信审通过" value="7" />
        <el-option label="合同待审" value="8" />
        <el-option label="待术后照" value="10" />
      </el-select>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter" style="margin-top:8px">
        查询
      </el-button>


    </div>

    <el-table :key="tableKey" v-loading="listLoading" :data="list" size="mini"  border fit highlight-current-row style="width: 100%;">
      <!-- <el-table-column label="ID" prop="id" align="center" width="80">
        <template slot-scope="{row}">
          <span>{{ row.order_id }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="签约时间" align="center"  width="85">
        <template slot-scope="{row}">
          <span>{{ row.pass_date }}</span>
        </template>
      </el-table-column>
      <el-table-column label="客户姓名" align="center"  width="100">
        <template slot-scope="{row}">
          <span>{{ row.real_name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="手机号码" align="center"  width="100">
        <template slot-scope="{row}">
          <span>{{ row.mobile }}</span>
        </template>
      </el-table-column>
      <el-table-column label="身份证号码" align="center" width="145">
        <template slot-scope="{row}">
          <span>{{ row.idcard }}</span>
        </template>
      </el-table-column>
      <el-table-column label="商户名称" align="center" width="300">
        <template slot-scope="{row}">
          <span>{{ row.merchant_name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="保理模式" align="center"  width="70">
        <template slot-scope="{row}">
          <span v-if="row.factoring_model==1" >正常</span>
          <span v-if="row.factoring_model==2" >买断</span>
          <span v-if="row.factoring_model==3" >绿通</span>
        </template>
      </el-table-column>
      <el-table-column label="通道" align="center"  width="50">
        <template slot-scope="{row}">
          <span v-if="row.loan_way==1" >保理</span>
          <span v-if="row.loan_way==2" >小贷</span>
        </template>
      </el-table-column>
      <el-table-column label="通过比例" align="center"  width="70">
        <template slot-scope="{row}">
          <span>{{ row.factoring_rate }}</span>
        </template>
      </el-table-column>
      <el-table-column label="订单状态" align="center"  width="100">
        <template slot-scope="{row}">
          <span>{{ row.order_status_name.str }}</span>
        </template>
      </el-table-column>


      <el-table-column label="签单员" class-name="status-col" width="70">
        <template slot-scope="{row}">
          {{ row.sale_name}}
        </template>
      </el-table-column>
      <el-table-column label="已付居间费" class-name="status-col" width="90">
        <template slot-scope="{row}">
          {{ row.mediate}}
        </template>
      </el-table-column>
      <el-table-column label="居间费比例" class-name="status-col" width="90">
        <template slot-scope="{row}">
          {{ row.mediate_pro}}
        </template>
      </el-table-column>
      <el-table-column label="服务模式" class-name="status-col" width="110">
        <template slot-scope="{row}">
          {{ row.mediate_way}}
        </template>
      </el-table-column>
      <el-table-column label="线上合同" class-name="status-col" width="70" >
        <template slot-scope="{row}" >
          <span :class="textcolor(row.esign_contract.first.lab)" @click="downloadContract(row.order_id,1)">{{ row.esign_contract.first.desc}}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="扣款协议" class-name="status-col" width="70" >
        <template slot-scope="{row}" >
          <span :class="textcolor(row.esign_contract.second.lab)" @click="downloadContract(row.order_id,2)">{{ row.esign_contract.second.desc}}</span>
        </template>
      </el-table-column> -->
      <!-- <el-table-column label="合同资料备注" class-name="status-col" v-if="nodes.indexOf('134')!=-1" width="200">
        <template slot-scope="{row}">
          <el-select v-model="row.contract_desc.ids" multiple placeholder="请选择" style="border:none" @change="changeDesc(row)">
            <el-option
              v-for="item in desc_list"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </template>
      </el-table-column> -->
      <el-table-column label="手术时间" class-name="status-col"  width="90">
        <template slot-scope="{row}">
          {{ row.operation_date}}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="100" class-name="small-padding fixed-width" >
        <template slot-scope="{row,$index}" v-if="row.is_paid!=1">
          <el-dropdown :hide-on-click="false" >
            <span class="el-dropdown-link" style="color:#67C23A">
              更多操作
              <i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item>
                <el-button size="mini" type="danger" @click="detail(row.order_id)" >
                  订单详情
                </el-button>
              </el-dropdown-item>
              <el-dropdown-item>
                 <el-button size="mini" type="primary" @click="mediate(row.order_id,row.mediate)" >
                  居间服务
                </el-button>
              </el-dropdown-item>
              <el-dropdown-item>
                <el-button  type="success" size="mini" v-if="row.order_status<11&&row.esign_contract.first.desc=='未签署'" @click="beforeOperation(row.order_id)">
                  发起签署
                </el-button>
                <el-button  type="warning" size="mini" v-else @click="beforeOperation(row.order_id)">
                  重新签署
                </el-button>
              </el-dropdown-item>
              <el-dropdown-item>
                <el-button size="mini" type="info" @click="toPaylist(row.order_id)" >
                  还款计划
                </el-button>
              </el-dropdown-item>
              <el-dropdown-item v-if="nodes.indexOf('154')!=-1">
                <el-button size="mini" type="default" @click="backLetter(row.order_id)" >
                  退回信审
                </el-button>
              </el-dropdown-item>

            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />


    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogOperationVisible" width="600px">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="120px" style="width: 300px; margin-left:70px;">
        <el-form-item label="手术时间" prop="real_name">
          <el-date-picker v-model="operationdata.date" style="width:150px;" format="yyyy-MM-dd" type="datetime" placeholder="手术日期" />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogOperationVisible = false">
          关闭
        </el-button>
        <el-button type="primary" @click="operationSubmit()">
           确认并发起合同
        </el-button>
      </div>
    </el-dialog>


    <el-dialog title="居间服务费" :visible.sync="dialogFormVisible" width="560px">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="120px" style="width: 70%; margin-left:70px;">
        <el-form-item label="已收居间服务费" prop="mediate">
          <el-input v-model="temp.paid_server" type="number" placeholder="请输入线下已收居间服务费" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="insertMediate()">
           确认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    fetchAllList,
    getBackendSignOrder,updateOrderDesc,
    fetchOrderRecordListByOrderId,
    operationSubmit,
    backLetter
  } from '@/api/order'
   import {
    downloadContract,getRegion,beforeOperation,insertMediate,backendgetmerchantregion
  } from '@/api/finance'
  import {
    getDesc
  } from '@/api/customer'
  
  import {
    formatDate
  } from '@/utils/formatDate.js'
  import waves from '@/directive/waves' // waves directive
  import {
    parseTime,getNodes
  } from '@/utils'
  import Pagination from '@/components/Pagination' // secondary package based on el-pagination
  export default {
    name: 'ComplexTable',
    components: {
      Pagination
    },
    directives: {
      waves
    },
    filters: {
      formatDate(time) {
        time = time * 1000
        let date = new Date(time)

        return formatDate(date, 'yyyy-MM-dd hh:mm:ss')
      }
    },
    data() {
      return {
        desc_list:[],
        dialogOperationVisible:false,
        tableKey: 0,
        operationdata:{
          date:'',
          order_id:''
        },
        tableRecord: 1,
        list: null,
        record_list: null,
        listRecordLoading: true,
        recordTotal: 0,
        total: 0,
        listLoading: true,
        listQuery: {
          page: 1,
          limit: 10,
          real_name: '',
          mobile: '',
          idcard: '',
          order_status: [7,13],
          order_s:'',
          descrition:'',
          order_date:'',
          city: '',
        },
        city: [],
        download: {
          order_id:''
        },
        temp: {
          order_id:'',
          paid_server:0,
        },
        rules: {
          real_name: [{
            required: true,
            message: '真实姓名必须填写',
            trigger: 'blur'
          }],
          mobile: [{
              required: true,
              message: '手机号码必须填写',
              trigger: 'blur'
            },
            {
              pattern: /^0{0,1}(13[0-9]|15[0-9]|153|156|18[0-9])[0-9]{8}$/,
              message: '手机号格式不对',
              trigger: 'blur'
            }
          ],
          idcard: [{
            required: true,
            message: '身份证号码必须填写',
            trigger: 'blur'
          }, {
            pattern: /(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{2}$)/,
            message: '证件号码格式有误！',
            trigger: 'blur'
          }],
          merchant_id: [{
            required: true,
            message: '合作商户必须选择',
            trigger: 'blur'
          }],
          sale_id: [{
            required: true,
            message: '销售人员必须选择',
            trigger: 'blur'
          }]
        },
        merchant_list: [],
        sale_list: [],
        listRecordQuery: {
          page: 1,
          limit: 20,
          order_id: ''
        },
        textMap: {
          record: '订单记录',
          create: 'Create'
        },
        dialogFormVisible: false,
        dialogRecordVisible: false,
        dialogStatus: '',
        downloadLoading: false,
        nodes:[]
      }
    },
    created() {
      this.cacheQueryFormat();
      this.getList();
      this.nodes = getNodes();
      //this.getDesc();
      this.getRegionList();
      //添加钩子，页面刷新
      window.addEventListener('beforeunload', e => this.beforeunloadFn(e))
    },
     mdestroyed() {
    //添加钩子，页面刷新
    window.removeEventListener('beforeunload', e => this.beforeunloadFn(e))
  },
  methods: {
      beforeunloadFn(e) {
        //刷新页面事件
        sessionStorage.removeItem('ordersign');
      },
      cacheQueryFormat(){
        let cacheQuery = sessionStorage.getItem('ordersign');
        if(cacheQuery){
          this.listQuery = JSON.parse(cacheQuery);
        }
      },
      beforeOperation(order_id) {
        this.$confirm(
          '确定要向客户发起术前合同签署吗?',
          '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
        ).then(() => {
          this.listLoading = true
          beforeOperation(order_id).then(response => {
            this.listLoading = false
            if(response.code==200){
              this.$notify({
                title: '提示',
                message: '发送成功',
                type: 'success',
                duration:2000
              });
              this.getList()
            }else{
               this.$notify({
                title: '提示',
                message: '网络错误',
                type: 'warning',
                duration:2000
              });
            }
          })
        })

      },
      backLetter(order_id) {
        this.$confirm(
          '确定要退回到信审吗?',
          '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
        ).then(() => {
          this.listLoading = true
          let pam = {order_id:order_id}
          backLetter(pam).then(response => {
            this.listLoading = false
            if(response.code==200){
              this.$notify({
                title: '提示',
                message: '成功',
                type: 'success',
                duration:2000
              });
              this.getList()
            }else{
               this.$notify({
                title: '提示',
                message: '网络错误',
                type: 'warning',
                duration:2000
              });
            }
          })
        })

      },

      getList() {
        sessionStorage.setItem('ordersign',JSON.stringify(this.listQuery))
        this.listLoading = true
        fetchAllList(this.listQuery).then(response => {
          this.list = response.data.data.data
          this.total = response.data.data.total
          this.merchant_list = response.data.sale_merchant.merchant
          setTimeout(() => {
            this.listLoading = false
          }, 1.0 * 1000)
        })
      },
      getRegionList() {
        backendgetmerchantregion(this.listQuery).then(response => {
          if (this.listQuery.city) {
            this.quyu = response.data
          } else {
            this.city = response.data
          }
        })
      },
      downloadContract(order_id,lab) {
        this.download.order_id = order_id;
        this.download.type = 1;
        downloadContract(this.download).then(response => {
          this.listLoading = false
          if(lab==1){
            if(response.data.first!=''){
              //window.location.href = response.data.first;
              window.open(response.data.first,'top');
            }
          }else{
            if(response.data.second!=''){
              //window.location.href = response.data.second;
              window.open(response.data.second,'top');
            }
          }
        })
      },
      textcolor(lab){
          if(lab==0){
            return 'pray';
            return '#909399'
          }
          if(lab==2){
             return 'green';
            return '#67C23A'
          }
          if(lab==3){
             return 'yellow';
            return '#E6A23C'
          }
          if(lab==4){
             return 'red';
            return '#F56C6C'
          }
      },
      // getDesc() {
      //   getDesc().then(response => {
      //     this.desc_list = response.data
      //   })
      // },
      changeDesc(row) {
        let querys = {};
        querys.order_id = row.order_id;
        querys.desc_ids = row.contract_desc.ids;
        updateOrderDesc(querys).then(response => {
          this.listLoading = false
           this.$notify({
                title: 'Success',
                message: 'Update Successfully',
                type: 'success',
                duration: 2000,
                onClose: this.getList()
              })
        })
      },
      handleFilter() {
        this.listQuery.page = 1;
        if(this.listQuery.order_s!=''){
          this.listQuery.order_status = [this.listQuery.order_s,this.listQuery.order_s];
        }
        this.getList()
      },

      getRecordList() {
        this.listRecordLoading = true
        fetchOrderRecordListByOrderId(this.listRecordQuery).then(response => {
          this.record_list = response.data.list
          this.recordTotal = response.data.count
          setTimeout(() => {
            this.listRecordLoading = false
          }, 1.0 * 1000)
        })
      },
      detail(order_id) {
        this.$router.push("/order/detail/" + order_id)
      },
      handleRecord(order_id) {
        console.log(order_id)
        this.dialogStatus = 'record'
        this.dialogRecordVisible = true
        this.listRecordQuery.order_id = order_id
        fetchOrderRecordListByOrderId(this.listRecordQuery).then(res => {
          this.record_list = res.data.list
          this.recordTotal = res.data.count
          setTimeout(() => {
            this.listRecordLoading = false
          }, 1.0 * 1000)

        })
      },
      operation(order_id) {
        this.dialogOperationVisible = true
        this.operationdata.order_id = order_id
      },
      operationSubmit() {
          if(this.operationdata.date==''){
            this.$notify({
              title: '提示',
              message: '请完善信息',
              type: 'warning',
              duration:2000
            });
            return;
          }
          this.dialogOperationVisible = false;
          this.listLoading = true;
          operationSubmit(this.operationdata).then(response => {
             this.listLoading = false
            if(response.code==200){
              this.$notify({
                title: '提示',
                message: '保存成功',
                type: 'success',
                duration:2000
              });
            }else{
               this.$notify({
                title: '提示',
                message: '网络错误',
                type: 'warning',
                duration:2000
              });
            }
          })
      },
      mediate(order_id,mediate){
        this.dialogFormVisible=true;
        this.temp.paid_server = mediate;
        this.temp.order_id = order_id;
      },
      insertMediate() {
        this.$confirm(
          '录入居间服务费将会生成或者重置还款计划表，确定要执行该操作吗?',
          '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
        ).then(() => {
          this.listLoading = true
          this.dialogFormVisible=false;
          insertMediate(this.temp).then(response => {
            this.listLoading = false
            if(response.code==200){
              this.$notify({
                title: '提示',
                message: '操作成功',
                type: 'success',
                duration:2000
              });
              this.getList();
            }else{
               this.$notify({
                title: '提示',
                message: '网络错误',
                type: 'warning',
                duration:2000
              });
            }
          })
        })
      },
      toPaylist(order_id) {
        this.$router.push('/order/customerpayment/' + order_id)
      },


    }
  }
</script>
<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    white-space: nowrap;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
    float: left;
  }
  .pray{color:#909399}
  .green{color:#67C23A;cursor: pointer;}
  .yellow{color:#E6A23C}
  .red{color:#F56C6C}
</style>
